#include "esp01s.h"
#include "string.h"

#define wifi_delay_ms delay_ms
#define wifi_send_data Uart1_SendStr
// #define sim_log_print printf

#define W_RX_BUFFER_SIZE 2048                // ���黺���С
uint8_t W_RxBuffer[W_RX_BUFFER_SIZE] = {0}; // ���ջ�������
uint16_t W_RxDataCnt = 0;                   // �����±�

#define WIFI_SSID "207"                                                                                           // WIFI�û���
#define WIFI_PASSWORD "12345678"                                                                                  // WIFI����
#define WIFI_AGREEMENT "TCP"                                                                                      // WIFI����Э��
#define WIFI_TARGET_IP "47.99.169.219"                                                                            // WIFI������IP 47.99.169.219
#define WIFI_TARGET_PORT "8080"                                                                                   // WIFI�������˿�
#define WIRELESS_WIFI_INFO "AT+CWJAP=\"" WIFI_SSID "\",\"" WIFI_PASSWORD "\"\r\n"                                 // ATָ�����2.4GHz wifi
#define CONNECT_SERVER_INFO "AT+CIPSTART=\"" WIFI_AGREEMENT "\",\"" WIFI_TARGET_IP "\"," WIFI_TARGET_PORT "\r\n " // ATָ����ӷ�����
#define DATA_TRANSPARTENT_MODE_INFO "AT+CIPMODE=1\r\n"                                                            // ATָ�͸��ģʽ
#define SEND_DATA_INFO "AT+CIPSEND\r\n"                                                                           // ATָ���������
Wifi_TypeDef Wifi_Status = {0, 0};

#define WEATHER_URL "restapi.amap.com"
#define WEATHER_TARGET_PORT "80"
#define WEATHER_SERVER_INFO "AT+CIPSTART=\"" WIFI_AGREEMENT "\",\"" WEATHER_URL "\"," WEATHER_TARGET_PORT "\r\n " // AT指令：连接服务器
#define GET_WEATHER_INFO "GET https://restapi.amap.com/v3/weather/weatherInfo?city=440100&key=2739fe14008d726480f75afc037bec39&extensions=all\r\n"

/**
 * @brief 位置信息获取
 *
 * @note city_data[2][32] 位置数据 [2]省份、城市  [32]表示每个数据最长32个字符
 * @note 调用时只需以字符串形式%s输出city_data[i]
 */
uint8_t city_data[2][32] = {0};
/**
 * @brief 天气信息获取
 *
 * @note weather_data[4][6][32] 天气数据 [4]表示4天 [6]表示每天6个数据  [32]表示每个数据最长32个字符
 * @note 数据包括： 日期、星期、日间天气、晚间天气、日间温度、晚间温度
 * @note 调用时只需以字符串形式%s输出weather_data[i][j]
 */
uint8_t weather_data[4][6][32] = {0};

uint8_t Wifi_get_receive_flag(void)
{
    uint8_t flag = Wifi_Status.receiveDataFlag;
    Wifi_Status.receiveDataFlag = 0;
    return flag;
}

uint8_t wifi_send_command(char *cmd, char *res, uint8_t sendCount, uint16_t delay_xms, uint8_t printf_enable)
{
    if (printf_enable == W_ENABLE)
        // sim_log_print("%s", cmd); // ������Դ�ӡÿ�η��͵�ָ��
        while (sendCount--)
        {
            wifi_send_data(cmd);                 // ATָ���
            wifi_delay_ms(delay_xms);            // �ʵ����ӵ��ӳ٣��ȴ����ڽ������
            if (Wifi_get_receive_flag() == W_OK) // ������ڽ��յ����лس�Ϊ��β������
            {
                if (strstr((const char *)W_RxBuffer, res) != NULL) // ���ҵ��ؼ���
                {
                    // sim_log_print("%s", res); // ������Դ�ӡÿ�η��͵�ָ��
                    wifi_clear_buffer(); // �������
                    return 1;            // �˳�������0-�ɹ�
                }
                // sim_log_print("error recovery data:%s", SIM_RxBuffer); // �����մ���ʱ����ӡ�����յ����ݣ��������
                wifi_clear_buffer();
            }
            wifi_delay_ms(500);
        }
    return 0; // ����1-ʧ��
}
/**
 * @brief SIM���ź�ǿ�ȼ��
 * @��Ӧʾ�� at+csq
            +CSQ: 12,99
            OK
 */

void wifi_init(void)
{
    // sim_log_print("Start SIM service\r\n");
	wifi_send_data("AT\r\n");
	delay_ms(50);
	wifi_send_data("+++");
	delay_ms(1000);
	wifi_send_data("AT+CIPCLOSE\r\n");
	delay_ms(50);
    if (wifi_send_command("AT+RST\r\n", "", 3, 500, W_ENABLE) != W_OK)
    {
        // sim_log_print("AT error\r\n");
        Wifi_Status.error_code |= (1 << 0);
    }
    if (wifi_send_command("ATE0\r\n", "OK", 3, 50, W_ENABLE) != W_OK)
    {
        // sim_log_print("No SIMCard\r\n");
        Wifi_Status.error_code |= (1 << 1);
    }
    if (wifi_send_command("AT+CWMODE=1\r\n", "OK", 3, 50, W_ENABLE) != W_OK)
    {
        // sim_log_print("No SIMCard\r\n");
        Wifi_Status.error_code |= (1 << 2);
    }

    if (wifi_send_command(WIRELESS_WIFI_INFO, "GOT IP", 3, 2000, W_ENABLE) != W_OK)
    {
        // sim_log_print("No SIMCard\r\n");
        Wifi_Status.error_code |= (1 << 3);
    }
    wifi_get_weather();
	wifi_connect_to_server();
}

void wifi_get_weather(void)
{
		if (Wifi_Status.error_code == 0x00)
    {
        if (wifi_send_command(WEATHER_SERVER_INFO, "OK", 3, 50, W_ENABLE) != W_OK)
            Wifi_Status.error_code |= (1 << 4);
        if (wifi_send_command(DATA_TRANSPARTENT_MODE_INFO, "OK", 3, 50, W_ENABLE) != W_OK)
            Wifi_Status.error_code |= (1 << 5);
        if (wifi_send_command(SEND_DATA_INFO, ">", 3, 50, W_ENABLE) != W_OK)
            Wifi_Status.error_code |= (1 << 6);
    }
    wifi_send_data(GET_WEATHER_INFO);
    wifi_delay_ms(1000);
    // Weather_analysis(W_RxBuffer,(uint8_t *)"\"dayweather\"",(uint8_t *)buff);
    print_weather_data();
    // 清空接收缓冲区
    wifi_clear_buffer();
    wifi_send_data((uint8_t *)"+++");
    wifi_delay_ms(1000);
		if (wifi_send_command("AT+CIPCLOSE\r\n", "OK", 3, 50, W_ENABLE) != W_OK)
    {
			Wifi_Status.error_code |= (1 << 10);
		}
    //    }
}

void wifi_connect_to_server(void)
{
    if (Wifi_Status.error_code == 0x00)
    {
        if (wifi_send_command(CONNECT_SERVER_INFO, "OK", 3, 50, W_ENABLE) != W_OK)
            Wifi_Status.error_code |= (1 << 7);
        if (wifi_send_command(DATA_TRANSPARTENT_MODE_INFO, "OK", 3, 50, W_ENABLE) != W_OK)
            Wifi_Status.error_code |= (1 << 8);
        if (wifi_send_command(SEND_DATA_INFO, ">", 3, 50, W_ENABLE) != W_OK)
            Wifi_Status.error_code |= (1 << 9);
    }
}

/**
 * @brief wifi�����·����������Է�������Ӧ����Ϣ��
 *       �·���SYN6288�����ϳ�
 *
 */
void wifi_data_issued(void)
{
	if(Wifi_Status.error_code == 0x00)
	{
		asr_proc();
		if (Wifi_get_receive_flag() == W_OK) 
		{
			SYN_FrameInfo(2, W_RxBuffer);
			wifi_clear_buffer();
		}
	}
}

void wifi_clear_buffer(void)
{
    memset(W_RxBuffer, 0, sizeof(W_RxBuffer));
    W_RxDataCnt = 0;
}


/******************解析 天气数据****************
形参：uint8_t* buff原始数据
            uint8_t *Weather_stat天气数据标志
            uint8_t *data解析获取到的数据
返回值：0---成功，其他值---失败
************************************************/
uint8_t Weather_analysis(uint8_t *buff, uint8_t *Weather_stat, uint8_t *data)
{
    char *p = NULL;
    uint16_t i = 0;
    p = strstr((char *)buff, (char *)Weather_stat);
    if (p)
    {
        p += strlen((char *)Weather_stat) + 2;
        i = 0;
        while (*p != '\"' && *p != '\0')
        {
            data[i++] = *p++;
        }
        data[i] = '\0';
        return 0;
    }
    else
        return 1;
}
/**
 * @brief 打印天气数据(用于调试)
 */
void print_weather_data()
{
    char *temp = NULL;
    Weather_analysis(W_RxBuffer, (uint8_t *)"\"province\"", city_data[0]);
    Weather_analysis(W_RxBuffer, (uint8_t *)"\"city\"", city_data[1]);
    printf("省份: %s\n", city_data[0]);
    printf("城市: %s\n", city_data[1]);
    // 第一天
    Weather_analysis(W_RxBuffer, (uint8_t *)"\"date\"", weather_data[0][0]);
    Weather_analysis(W_RxBuffer, (uint8_t *)"\"week\"", weather_data[0][1]);
    Weather_analysis(W_RxBuffer, (uint8_t *)"\"dayweather\"", weather_data[0][2]);
    Weather_analysis(W_RxBuffer, (uint8_t *)"\"nightweather\"", weather_data[0][3]);
    Weather_analysis(W_RxBuffer, (uint8_t *)"\"daytemp\"", weather_data[0][4]);
	sprintf((char*)weather_data[0][4],"%s摄氏度",weather_data[0][4]);
    Weather_analysis(W_RxBuffer, (uint8_t *)"\"nighttemp\"", weather_data[0][5]);
    temp = strstr((const char *)W_RxBuffer, "nighttemp_float");
    // 第二天
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"date\"", weather_data[1][0]);
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"week\"", weather_data[1][1]);
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"dayweather\"", weather_data[1][2]);
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"nightweather\"", weather_data[1][3]);
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"daytemp\"", weather_data[1][4]);
	sprintf((char*)weather_data[1][4],"%s摄氏度",weather_data[1][4]);
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"nighttemp\"", weather_data[1][5]);
    temp = strstr(temp, "daytemp_float");
    // 第三天
    // temp = strstr(temp,"date");
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"date\"", weather_data[2][0]);
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"week\"", weather_data[2][1]);
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"dayweather\"", weather_data[2][2]);
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"nightweather\"", weather_data[2][3]);
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"daytemp\"", weather_data[2][4]);
	sprintf((char*)weather_data[2][4],"%s摄氏度",weather_data[2][4]);
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"nighttemp\"", weather_data[2][5]);
    temp = strstr(temp, "nightpower");
    // 第四天

    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"date\"", weather_data[3][0]);
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"week\"", weather_data[3][1]);
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"dayweather\"", weather_data[3][2]);
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"nightweather\"", weather_data[3][3]);
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"daytemp\"", weather_data[3][4]);
	sprintf((char*)weather_data[3][4],"%s摄氏度",weather_data[3][4]);
    Weather_analysis((uint8_t *)temp, (uint8_t *)"\"nighttemp\"", weather_data[3][5]);

//     uint8_t day = 0;
//    for (day = 0; day < 4; day++)
//    {
//        if (weather_data[day][0][0] == '\0')
//            break; // 没有数据则停止
//         if(strstr(weather_data[day][1],"1"))
//             strcpy(weather_data[day][1],"星期一");
//         else if(strchr(weather_data[day][1],'2'))
//             strcpy(weather_data[day][1],"星期二");
//         else if(strstr(weather_data[day][1],"3"))
//             strcpy(weather_data[day][1],"星期三");
//         else if(strstr(weather_data[day][1],"4"))
//             strcpy(weather_data[day][1],"星期四"); 
//         else if(strstr(weather_data[day][1],"5"))
//             strcpy(weather_data[day][1],"星期五");
//         else if(strstr(weather_data[day][1],"6"))
//             strcpy(weather_data[day][1],"星期六");
//         else if(strstr(weather_data[day][1],"7"))
//             strcpy(weather_data[day][1],"星期天");
//    }
}

void wifi_receive_callback(uint8_t byte)
{
    W_RxBuffer[W_RxDataCnt++] = byte;   
    if (W_RxDataCnt > W_RX_BUFFER_SIZE) 
    {
        wifi_clear_buffer();
    }
    if (W_RxDataCnt >= 2 && (W_RxBuffer[W_RxDataCnt - 2] == '\r' && W_RxBuffer[W_RxDataCnt - 1] == '\n')) // �жϽ���λ
    {
        Wifi_Status.receiveDataFlag = 1;
    }
}
